package com.woniuxy.lrz.carlproject.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e){
        log.warn("e:.."+e.getMessage(),e);
        if(e instanceof MethodArgumentNotValidException){
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            if(bindingResult.hasErrors()){
                StringBuilder errorMsgBuilder = new StringBuilder();
                List<FieldError> fieldErrors = bindingResult.getFieldErrors();
                for (FieldError e1 : fieldErrors){
                    errorMsgBuilder.append(e1.getField()+":"+e1.getDefaultMessage()+";");
                }
                return Result.error("502",errorMsgBuilder.toString());
            }
        }
        if(e instanceof HttpMessageNotReadableException){
            log.warn("e:.."+e.getMessage(),e);
            return Result.error("503",e.getMessage());
        }
        return Result.error();
    }
    @ExceptionHandler(AppException.class)
    public Result handleAppException(AppException e){
        log.warn("e:.."+e.getMessage(),e);
        return Result.error("501",e.getMsg());
    }


    protected String getErrorMsg(BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            StringBuilder errorMsgBuilder = new StringBuilder();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError e : fieldErrors){
                errorMsgBuilder.append(e.getField()+":"+e.getDefaultMessage()+";");
            }
            return errorMsgBuilder.toString();
        }
        return null;
    }
}